import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, roc_auc_score, confusion_matrix
from sklearn.model_selection import train_test_split

# ========== 1. 数据读取 ==========
# df = pd.read_csv(r"D:\resources\2014_to_2021_E7_depth150_label_each_month_tertile.csv")
df = pd.read_csv(r"D:\resources\data\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD_each_year_tertile.csv")
# df = pd.read_csv(r"D:\resources\2014_to_2021_E7_depth150_label_each_year_tertile.csv")
# df = pd.read_csv(r"D:\resources\data\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD_each_month_tertile.csv")
# df = pd.read_csv(r"D:\resources\data\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD_each_year_median.csv")
# df = pd.read_csv(r"D:\resources\data\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD_each_month_median.csv")
# df = pd.read_csv(r"D:\resources\data\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD.csv")

# ========== 2. 特征与标签 ==========
target_col = "Label"  # 渔场类别列（0=低产，1=高产）

# 要排除的列
exclude_cols = ['Catch', 'Effort', 'CPUE', 'Label']

# 特征列 = 除去上述列
feature_cols = [col for col in df.columns if col not in exclude_cols]
# feature_cols = [ 'ST_0', 'DO_0', 'Year', 'ST_50', 'MLD', 'Month', 'SSS_100', 'SSH', 'CHL', 'ST_200', 'ST_150', 'Lon', 'ST_500', 'DO_50', 'SSS_150']

# categorical_cols = [
#     'Year', 'Month'
# ]
#
# for col in categorical_cols:
#     df[col] = df[col].astype('category')


X = df[feature_cols].copy()
y = df[target_col].astype(int)  # 确保是整型分类标签

# numeric_cols = [col for col in X.columns if col not in categorical_cols]
# scaler = MinMaxScaler()
# X[numeric_cols] = scaler.fit_transform(X[numeric_cols])

# ========== 3. 数据划分 ==========
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

# ========== 4. 训练 EBM 分类模型 ==========
ebm = RandomForestClassifier(
    n_estimators=300,
    max_depth=5,
    min_samples_leaf=1,
    min_samples_split=2,
    max_features='sqrt',
    random_state=42
)

print(ebm.get_params())

ebm.fit(X_train, y_train)

# ========== 5. 预测与指标 ==========
y_pred = ebm.predict(X_test)
y_proba = ebm.predict_proba(X_test)[:, 1]

acc = accuracy_score(y_test, y_pred)
prec = precision_score(y_test, y_pred)
rec = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
auc = roc_auc_score(y_test, y_proba)

print("\n🎯 RF 分类模型评估结果 (测试集)")
print(f"Accuracy = {acc:.4f}")
print(f"Precision = {prec:.4f}")
print(f"Recall = {rec:.4f}")
print(f"F1-score = {f1:.4f}")
print(f"ROC-AUC = {auc:.4f}")

print("\n混淆矩阵：")
print(confusion_matrix(y_test, y_pred))
